define(function(require, exports, module){
	require("oa/act/approval/form/css/form.css");
	require("resource/js/easyui/easyloader.js");
	var ajax = require("resource/js/component/ajax.js");
	
	Date.prototype.format = function (fmt) { //author: meizz 
	    var o = {
	        "M+": this.getMonth() + 1, //月份 
	        "d+": this.getDate(), //日 
	        "h+": this.getHours(), //小时 
	        "m+": this.getMinutes(), //分 
	        "s+": this.getSeconds(), //秒 
	        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	        "S": this.getMilliseconds() //毫秒 
	    };
	    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	    for (var k in o)
	    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	    return fmt;
	}
	
	var rightspan ,duty_form ,temphtml='<div class="jgui-row jgui-form-item jgui-form-no-colon"><div class="jgui-form-item-label"></div><div class="jgui-form-item-wrapper"><div class="jgui-form-item-control "><span class="jgui-input-wrapper"></span></div></div></div>';
	//标题
	var callbytitle = function(options){
		var temp = $(temphtml),textlabel=$(this).find(".jgui-form-item-label>label");
		$('<label class="jgui-form-item-required" >标题</label>').appendTo(temp.find(".jgui-form-item-label"));
		$('<input type="text" class="jgui-input jgui-input-lg">')
		.appendTo(temp.appendTo(duty_form).find("span.jgui-input-wrapper"))
		.on("input click",function(){
			options.col_name_ch = this.value;
			textlabel.text(this.value);
		}).val(options.col_name_ch).click();
	}
	//提示信息
	var callbyprompt = function(options){
		var temp = $(temphtml),textprompt=$(this).find(".jgui-input");
		$('<label class="">提示信息</label>').appendTo(temp.find(".jgui-form-item-label"));
		$('<input type="text"  class="jgui-input jgui-input-lg"><div style="font-size:12px;color:#9e9e9e;">注意：不支持单引号，双引号等特殊字符</div>')
		.appendTo(temp.appendTo(duty_form).find("span.jgui-input-wrapper"))
		.keyup(function(){
			this.value = this.value.replace(/\'|\"|(&apos;)|(&quot;)|(\\')|(\\")/g,'');//不允许输入单引号或双引号
		})
		.on("input click",function(){
			var val = this.value
			if(val && val.length>0){
				options.properties="{prompt:'"+val+"'}";
			}else{
				options.properties="";
			}			
			textprompt.attr("placeholder",val);
		}).val(textprompt.attr('placeholder')).click();
	}
	//必填项
	var callbyrequire = function(options){
		var temp = $(temphtml),textrequire=$(this).find(".jgui-form-item-label>label");
		$('<label class="">是否必填</label>').appendTo(temp.find(".jgui-form-item-label"));
		$('<div><label class="jgui-radio-input"><input type="radio" name="on" value="0">是</label><label class="jgui-radio-input"><input type="radio" name="on" value="1">否</label></div>')
		.appendTo(temp.appendTo(duty_form).find("span.jgui-input-wrapper"))
		.find("input")
		.on("click",function(){
			options.is_require = this.value;
			if(this.value=="0"){
				textrequire.addClass("jgui-form-item-required");
			}else{
				textrequire.removeClass("jgui-form-item-required");
			}
		}).each(function(){
			if(this.value==options.is_require){
				$(this).prop("checked",true);
				$(this).click();
				return false;
			}
		});
		
	}
	//日期类型
	var callbydatetype = function(options){
		var temp = $(temphtml),textbox=$(this).find(".jgui-input");
		$('<label class="">日期格式</label>').appendTo(temp.find(".jgui-form-item-label"));
		$('<div><label class="jgui-radio-input"><input type="radio" name="datetype" value="datetimebox">年-月-日 时:分:秒</label><label class="jgui-radio-input"><input type="radio" name="datetype" value="datebox">年-月-日</label></div>')
		.appendTo(temp.appendTo(duty_form).find("span.jgui-input-wrapper"))
		.find("input")
		.on("click",function(){
			options.show_type = this.value;
			if(options.show_type=="datetimebox"){
				textbox.val(new Date().format('yyyy-MM-dd hh:mm:ss'));
			}else{
				textbox.val(new Date().format('yyyy-MM-dd'));
			}
		})
		.each(function(){
			if(this.value==options.show_type){
				$(this).prop("checked",true);
				$(this).click();
				return false;
			}
		});
	}
	//下拉选项
	var callbyselect = function(options){
		var temp = $(temphtml),selectbox=$(this).find("select");
		$('<label class="">选项设置</label>').appendTo(temp.find(".jgui-form-item-label"));
		$('<textarea type="textarea" Placeholder="例：选项一，选项二" class="jgui-input jgui-input-lg" style="min-height: 70px;"></textarea><div style="font-size:12px;color:#9e9e9e;">备注：选项之间用逗号或分号分隔</div>')
		.appendTo(temp.appendTo(duty_form).find("span.jgui-input-wrapper"))
		.on("input click",function(){
			options.data_id = this.value.replace(/[','|'，'|';'|'；']/g,',');
			selectbox.empty();
			var opts = $.unique(options.data_id.split(','));
			for(var i in opts){
				if(opts[i].trim()!=""){
					selectbox.append("<option>"+opts[i]+"</option>");
				}
			}
		}).val(options.data_id).click();
		
	}
	
	//多选项
	var callbyismutil = function(options){
		var temp = $(temphtml),selectbox=$(this).find("select");
		$('<label class="">是否多选</label>').appendTo(temp.find(".jgui-form-item-label"));
		$('<div><label class="jgui-radio-input"><input type="radio" name="select" value="mselect">是</label><label class="jgui-radio-input"><input type="radio" name="select" value="select">否</label></div>')
		.appendTo(temp.appendTo(duty_form).find("span.jgui-input-wrapper"))
		.find("input")
		.on("click",function(){
			options.show_type = this.value;
			if("mselect"==this.value){
				selectbox.attr("multiple","multiple");
			}else{
				selectbox.removeProp("multiple");
			}
		}).each(function(){
			if(this.value==options.show_type){
				$(this).prop("checked",true);
				$(this).click();
				return false;
			}
		});
	}
	
	var controls = {
		text:{text:'单行文本',view:'<span class="jgui-input-wrapper"><input type="text" placeholder="" class="jgui-input jgui-input-lg" value=""></span>',
			onClick:function(){
				rightspan.removeClass("jgui-drawer-close").addClass("jgui-drawer-open");
				duty_form.empty();
				var options = $.data(this,"options");
				callbytitle.call(this,options);
				callbyprompt.call(this,options);
				callbyrequire.call(this,options);
			}
		},
		textarea:{text:'多行文本',view:'<span class="jgui-input-wrapper"><textarea type="textarea" placeholder="" class="jgui-input jgui-input-lg"></textarea></span>',
			onClick:function(){
				rightspan.removeClass("jgui-drawer-close").addClass("jgui-drawer-open");
				duty_form.empty();
				var options = $.data(this,"options");
				callbytitle.call(this,options);
				callbyprompt.call(this,options);
				callbyrequire.call(this,options);
			}
		},
		number:{text:'数字',view:'<span class="jgui-input-wrapper"><input type="number" placeholder="" class="jgui-input jgui-input-lg" value=""></span>',
			onClick:function(){
				rightspan.removeClass("jgui-drawer-close").addClass("jgui-drawer-open");
				duty_form.empty();
				var options = $.data(this,"options");
				callbytitle.call(this,options);
				callbyprompt.call(this,options);
				callbyrequire.call(this,options);
			}
		},
		select:{text:'下拉菜单',view:'<div class="jgui-select-lg jgui-select jgui-select-enabled" style="width: 200px;"><select class="jgui-input" placeholder="" ></select></div>',
			onClick:function(){
				rightspan.removeClass("jgui-drawer-close").addClass("jgui-drawer-open");
				duty_form.empty();
				var options = $.data(this,"options");
				callbytitle.call(this,options);
				callbyprompt.call(this,options);
				callbyselect.call(this,options);
				callbyismutil.call(this,options);
				callbyrequire.call(this,options);
			},
			onCreate:function(options){
				var selectbox = this.find("select");
				options.data_id = defaultoptions.data_id||"选项一,选项二";
				var opts = options.data_id.split(',');
				selectbox.empty();
				
				for(var i in opts){
					if(opts[i].trim()!=""){
						selectbox.append("<option>"+opts[i]+"</option>");
					}
				}
				if(options.show_type=="mselect"){
					this.find("select").attr("multiple","multiple")
				}
			}
		},
		datebox:{text:'日期',view:'<span class="jgui-calendar-picker"><span><input disabled="" readonly="" value="2016-11-24" class="jgui-calendar-range-picker jgui-input jgui-input-lg"><span class="jgui-calendar-picker-icon"></span></span></span>',
			onClick:function(){
				rightspan.removeClass("jgui-drawer-close").addClass("jgui-drawer-open");
				duty_form.empty();
				var options = $.data(this,"options");
				callbytitle.call(this,options);
				callbyprompt.call(this,options);
				callbydatetype.call(this,options);
				callbyrequire.call(this,options);
			}
		},
		file:{text:'附件',view:'<div><button type="button" style="width:100px;" class="jgui-input jgui-btn jgui-btn-button"><i type="paper-clip" class="jgicon jgicon-paper-clip"></i><span>上传附件</span><i type="down" class="jgicon jgicon-down"></i></button></div>',
			onClick:function(){
				rightspan.removeClass("jgui-drawer-close").addClass("jgui-drawer-open");
				duty_form.empty();
				var options = $.data(this,"options");
				callbytitle.call(this,options);
				callbyprompt.call(this,options);
				callbyrequire.call(this,options);
			}
		}
	};
	
	var formtag,closehtml = '<span class="icon-alertoff_black close"></span>',dragele,defaultoptions={};
	var initPage = function(){
		var controlspan = $(".fieldsetbox-wrapper");
		formtag = $(".formdrag").off("dragover dragenter drop").on("dragover",function(ev){
			ev.preventDefault();
			return true;
		}).on("dragenter",function(ev) {
			if(ev.target!=formtag[0])
				return;

			if($(dragele).hasClass("fieldsetbox-item")){
				return;
			}
			
			var target,height=0;
			$(ev.target).children().each(function(){
				target = $(this);
				height+=$(this).outerHeight();
				if(height>=ev.originalEvent.offsetY){
					return false;
				}
			});
			$(dragele).insertBefore(target);
			return true;
		}).on("drop",function(ev) {
			if(ev.target!=formtag[0])
				return;
			if($(dragele).hasClass("fieldsetbox-item")){
				$(dragele).click();
				dragele = $(ev.target).children().last();
			}
			var target,height=0;
			$(ev.target).children().each(function(){
				target = $(this);
				height+=$(this).outerHeight();
				if(height>=ev.originalEvent.offsetY){
					return false;
				}
			});
			$(dragele).insertBefore(target);
			return false;
		});
		
		rightspan = $(".jgui-drawer-right");
		duty_form = rightspan.find(".duty_form");
		
		var i=0;
		for(var key in controls){
			$.data($('<div draggable="true" type="'+key+'" class="fieldsetbox-item" style="left: '+i+'px; cursor: pointer;"> <span class="fieldsetbox-item-text">'+controls[key].text+'</span> </div>')
					.appendTo(controlspan)
					.off("dragstart click")
					.on("dragstart",function(ev){					
						dragele = this;
					})
					.on("click",function(){
						if(formtag.attr("class")=="formdrag"){
							formtag.empty().attr("class","formdragtag");
						}
						var option = $.data(this,"control");
						var formfield = $('<div class="formfield-wrap"><div class="tags" draggable="true"><div class="jgui-row jgui-form-item jgui-form-no-colon"><div class="jgui-form-item-label"><label class="">'+option.text+'</label></div><div class="jgui-form-item-wrapper"><div class="jgui-form-item-control ">'+option.view+'</div></div></div></div></div>')
						.appendTo(formtag)
						.off("dragstart click")
						.on("dragstart",function(){
							dragele = this;
						})
						.on("click",option.onClick);
						var dataoption = $.extend(true,{},{col_name_ch:option.text,is_require:"1",show_type:$(this).attr("type"),properties:'{prompt:\'\'}'},defaultoptions);
						if(option.onCreate)
							option.onCreate.call(formfield,dataoption);
						
						$(window).resize();
						$.data(formfield[0],"options",dataoption);
						if(dataoption.is_require.toString().trim()=="0"){
							formfield.find(".jgui-form-item-label label").addClass("jgui-form-item-required");
						}
						
						$(closehtml).prependTo(formfield.children()).click(function(e){
							e.stopPropagation();
							$(this).closest(".formfield-wrap").remove();
						});
					})[0],"control",controls[key]);
			i+=90;
		}
		rightspan.find(".close").click(function(){
			rightspan.addClass("jgui-drawer-close").removeClass("jgui-drawer-open");
		});
	}
	module.exports={
		init:function(){
			if(encrypt){//encrypt是页面入口传入，以区分新建和更新，更新表单没有加密设置
				$('#encryptForm').show();
			}else{
				$('#encryptForm').hide();
			}
			initPage();
			//初始化表单数据
			$("#form_name").val(formdata.form_name||"");
			$("#form_des").val(formdata.form_des||"");
			for(var key in formdata.cols){
				defaultoptions = formdata.cols[key];
				var properties = formdata.cols[key].properties;
//				if(!formdata.cols[key].properties)
//					formdata.cols[key].properties = "{prompt:''}";
				if(properties && typeof formdata.cols[key].properties == "string"){
					try{
						//formdata.cols[key].properties = JSON.parse(formdata.cols[key].properties);
						properties = eval("("+formdata.cols[key].properties+")");
					}catch(e){
						properties = eval("("+formdata.cols[key].properties+")");
					}
				}
				var find = formdata.cols[key].show_type;
				if(find=="mselect"){
					find = "select";
				}
				if(find=="datetimebox")
					find = "datebox";
				$("div[type='"+find+"']").click();
				formtag.find(".formfield-wrap").last().find("label").text(formdata.cols[key]["col_name_ch"]);
				formtag.find(".jgui-form-item-label label").last().addClass(formdata.cols[key].is_require=="0"?"jgui-form-item-required":"");
				
				formtag.find(".formfield-wrap").last().find(".jgui-form-item-control").children().children().attr("placeholder",properties&&properties.prompt||"");
				if(formdata.cols[key].show_type=="datetimebox"){
					formtag.find(".formfield-wrap").last().find(".jgui-form-item-control").find("input").val(new Date().format('yyyy-MM-dd hh:mm:ss'));
				}
			}
			defaultoptions = {};
			//btn_submit
			$("#btn_submit").on("click",function(){
				formdata.form_name = $("#form_name").val();
				if(formdata.form_name.trim()==""){
					using("messager",function(){
						$.messager.alert("系统提示","表单名称不能为空！");
					});
					return;
				}
				formdata.form_des = $("#form_des").val();
				if(encrypt){//encrypt是页面入口传入，以区分新建和更新，更新表单没有加密设置
					formdata.encrypt = $('input[name="encrypt"]:checked').val();
				}
				formdata.cols = [];
				try{
					formtag.children().each(function(){
						formdata.cols.push($.data(this,"options"));
						if($.data(this,"options").col_name_ch.trim()==""){
							throw "表单字段名称不能为空！";
						}
					});
					if(formdata.cols.length===0){
						using("messager",function(){
							$.messager.alert("系统提示","表单控件不能为空！");
						});
						return;
					}
					ajax.init().success(function(c,m,d){
						using("messager",function(){
							$.messager.alert("系统提示",m,'',function(){
								var center = $("body").layout().layout("panel","center");
								center.panel("refresh",BASEPATH+"/view/oa/act/approval/form/formview");
							});
						});
					}).post(submitaddress,{details:JSON.stringify(formdata)});
				}catch(e){
					using("messager",function(){
						$.messager.alert("系统提示",e);
					});
				}
			});
			
			$(window).on("resize",function(){
				if($(".formdrag").length>0){
					formtag.css("min-height",document.body.offsetHeight-380);
				}else{
					formtag.css("min-height",document.body.offsetHeight-380);
				}
			});
			
			$(window).resize();
			$(".pull-left").click(function(){
				var center = $("body").layout().layout("panel","center");
				center.panel("refresh",BASEPATH+"/view/oa/act/approval/form/formview");
			});

			$("#btn_preview").click(function(){
				formdata.form_name = $("#form_name").val();
				formdata.form_des = $("#form_des").val();
				formdata.cols = [];
				formtag.children().each(function(){
					formdata.cols.push($.data(this,"options"));
					if($.data(this,"options").col_name_ch.trim()==""){
						throw '表单字段异常！';
					}
				});
				var form = $("<div><h2 style='text-align:center'>"+formdata.form_name+"</h2></div>");
				for(var key in formdata.cols){
					var row = $('<div class="jgui-row jgui-form-item jgui-form-no-colon"><div class="jgui-form-item-label"><label class="'+(formdata.cols[key].is_require=="0"?"jgui-form-item-required":"")+'">'+formdata.cols[key].col_name_ch+'</label></div><div class="jgui-form-item-wrapper"><div class="jgui-form-item-control "></div></div></div>').appendTo(form);
					var find = formdata.cols[key].show_type;
					if(formdata.cols[key].show_type == "mselect")
						find = "select";
					if(formdata.cols[key].show_type == "datetimebox")
						find = "datebox";
					
					var view = $(controls[find].view).appendTo(row.find(".jgui-form-item-control"));
					if("mselect".indexOf(formdata.cols[key].show_type)!=-1){
						if(formdata.cols[key].show_type=="mselect")
							view.find("select").attr("multiple","multiple");
						$.each(formdata.cols[key].data_id.split(/[','|'，'|';'|'；']/),function(i,item){
							$("<option>"+item+"</option>").appendTo(view.find("select"));
						});
					}
					if(formdata.cols[key].show_type == "datetimebox"){
						view.find("input").val(new Date().format('yyyy-MM-dd hh:mm:ss'));
					}
					var properties = formdata.cols[key].properties;
					if(properties && typeof formdata.cols[key].properties == "string"){
						try{
							properties = eval("("+formdata.cols[key].properties+")");
						}catch(e){
							properties = eval("("+formdata.cols[key].properties+")");
						}
					}
					view.find(".jgui-input").attr("placeholder",properties&&properties.prompt||"");
				}
				$("#prewgld").dialog("body").empty().append(form).dialog("open");
				$(".from-mask").css({'z-index': parseInt($("#prewgld").parent().css('z-index'))-1}).show();
			});
			$("#prewgld").parent().find('.panel-tool-close').click(function(){
				$(".from-mask").hide();
			});
		}
	}
});